/*
 * Golazo MA4
 * Copyright (C) 2008 Golazo MASHUP AWARD 4th team.
 * http://code.google.com/p/golazo/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * checkNote
 */
function checkNote() {
  
  var note = $('#form_note');
  var message = $('#form_message');

  if (!Golazo.Action.checkNote(note.val())) {
	message
	  .text('メモに誤りがあります。1～4,096文字で入力してください。');
	return false;
  }

  return true;
};
//checkNote.runat = 'both';

/**
 * serverload
 */
function serverload() {

  // ignore
  Jaxer.response.setClientFramework();

  // dispatch 
  Golazo.dispatch(function(request, response, session) {

    // 私は誰か
    var me = Golazo.User.find(session.get('me'));
	if (!me)
	  return $('#signin')
	    .layout(/*me*/)
		.gpsone();

    // GPS の緯度
    var lat = request.data.lat;
	if (typeof(lat) !== 'undefined')
	  lat = Golazo.Geo.dmsToDegree(lat);

    // GPS の経度
    var lon = request.data.lon;
	if (typeof(lon) !== 'undefined')
	  lon = Golazo.Geo.dmsToDegree(lon);
	
	if (lat && lon) {
	  
	  var log;
	  try {
        
        // ログを記録する
		log = new Golazo.UserLog(me);
        log.latitude = lat;
        log.longitude = lon;
        log.save();

      } catch (e) {
        throw new Error(''+e);
      }
	}

    // メモ
    var note = $('#form_note')
      .val(request.data.note || '');

    // 現在地の緯度
    var latitude = $('#form_latitude')
      .val(lat || request.data.latitude || '');
      
    if (!Golazo.Action.checkLatitude(latitude.val()))
  	  return $('#where')
	    .layout(me)
		.gpsone();

    // 現在地の経度
    var longitude = $('#form_longitude')
      .val(lon || request.data.longitude || '');

    if (!Golazo.Action.checkLongitude(longitude.val()))
  	  return $('#where')
	    .layout(me)
		.gpsone();

    // 現在地
	var where = {
	  latitude: latitude.val(),
	  longitude: longitude.val(),
	  altitude: Golazo.WHERE_TOKYO.altitude
	};

    // 現在地の地図
    $('img.map')
      .staticmaps(where.latitude, where.longitude, where.altitude);

    // メモの購読者 -- Jaxer は同名パラメータに未対応のため
	var subscribers = [];
	request.postData.split('&').forEach(function(param) {
	  param = param.split('=');
	  if (param[0] == 'subscriber')
	    subscribers.push(decodeURIComponent(param[1] || ''));
	});

    // 私を信頼する人を検索する
    var trustedTo = me.findByTrustedTo();

    // 私を信頼する人かどうか
    subscribers = Golazo.findAll(subscribers, function(subscriber) {
      return !!Golazo.find(trustedTo, function() {
        return this.equals(subscriber);
      });
    });

    // 私を信頼する人をリスト表示する
    trustedTo.forEach(function(user) {
	  
	  if (Golazo.find(subscribers, function() {
        return user.equals(this);
      })) {
        user.subscribed = {};
      }
							   
	  var input = $('<input type="checkbox" />')
		.attr('name', 'subscriber')
		.attr('value', user.userId)
		.attr('checked', !!user.subscribed); 
      
	  $('#subscribers')
		.append(input)
		.append(user.nickname || user.userId)
		.append('<br />');
    });

    // ココメモの先頭
    $('a.head')
      .attr('href', '/ez/me.html?' + $.param({
   	    latitude: latitude.val(),
		longitude: longitude.val()
	  }));

    // GET
    if (request.method != 'POST') {

	  return $('#form')
	    .layout(me)
		.gpsone();

	// POST  
	} else {

      // メモは期待どおりか
	  if (!checkNote())
        return $('#form')
		  .layout(me)
		  .gpsone();

      var action;
      try {

        // メモを保存する
	    action = new Golazo.Action(me);
        action.note = note.val();
        action.latitude = where.latitude; 
        action.longitude = where.longitude;
        action.altitude = where.altitude;
	    action.save();
	
	    // メモを購読する
	    action.subscribe(me);

        // メモを購読する
        subscribers.forEach(function(subscriber) {
          action.subscribe(subscriber);
        });

      } catch (e) {
	    throw new Error(''+e);
      }

      return $('#succeeded')
	    .layout(me)
		.gpsone();
    }
  });
};

/**
 * load
function load(layout) {
};
load.runat = 'client';
 */
